package com.qire.manhua.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.qire.other.thirdPlatform.WeChatPlatform;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
	
	private static final String TAG = "WXPayEntryActivity";

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		WeChatPlatform.WeChat.weChatApi().handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		WeChatPlatform.WeChat.weChatApi().handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {

	}

	@Override
	public void onResp(BaseResp resp) {
		Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			PayResp payReq = (PayResp) resp;
			Bundle data = new Bundle();
			data.putString("extData", payReq.extData);

			switch (resp.errCode) {
				case BaseResp.ErrCode.ERR_OK:
					Toast.makeText(this, "支付成功", Toast.LENGTH_LONG).show();
					data.putInt("resultCode", WeChatPlatform.PAY_SUCCESS);

					Message okMsg = Message.obtain();
					okMsg.what = WeChatPlatform.MSG_PAY_BACK;
					okMsg.setData(data);
					WeChatPlatform.WeChat.sendMessage(okMsg);
					break;
				case BaseResp.ErrCode.ERR_USER_CANCEL:
					Toast.makeText(this, "支付被取消", Toast.LENGTH_LONG).show();
					data.putInt("resultCode", WeChatPlatform.PAY_CANCEL);

					Message cancelMsg = Message.obtain();
					cancelMsg.what = WeChatPlatform.MSG_PAY_BACK;
					cancelMsg.setData(data);
					WeChatPlatform.WeChat.sendMessage(cancelMsg);
					break;
				case BaseResp.ErrCode.ERR_COMM:
				case BaseResp.ErrCode.ERR_SENT_FAILED:
				case BaseResp.ErrCode.ERR_AUTH_DENIED:
				case BaseResp.ErrCode.ERR_UNSUPPORT:
				case BaseResp.ErrCode.ERR_BAN:
					Toast.makeText(this, "支付错误", Toast.LENGTH_LONG).show();
					data.putInt("resultCode", WeChatPlatform.PAY_ERROR);

					Message errorMsg = Message.obtain();
					errorMsg.what = WeChatPlatform.MSG_PAY_BACK;
					errorMsg.setData(data);
					WeChatPlatform.WeChat.sendMessage(errorMsg);
					break;
			}
		}
		onBackPressed();
	}

}